#include "Coordinate.h"
namespace SLG
{
	Coordinate::Coordinate(uint32 x,uint32 y)
		:m_screenWidth(x),
		m_screenHeight(y)
	{
		m_hscreenWidth=x/2;
		m_hscreenHeight=y/2;
		m_Camera=NULL;
	}

	Coordinate::~Coordinate(void)
	{
	}

	void Coordinate::AddCamera(Camera* c)
	{
		m_Camera=c;
	}

	Ray* Coordinate::ScreenToWorldCoord(D3DXVECTOR2* p)
	{
		assert(m_Camera);
		float dx=(p->x/(float)m_hscreenWidth-1.0f)*m_Camera->m_aspect;
		float dy=(1.0f-p->y/m_hscreenHeight);
		float tmp=tanf(m_Camera->m_fovy/2);
		D3DXMATRIX invMatrix;
		D3DXMatrixInverse(&invMatrix,NULL,m_Camera->GetViewMatrix());
		D3DXVECTOR3 p1=D3DXVECTOR3(dx*m_Camera->m_zn*tmp,dy*m_Camera->m_zn*tmp,m_Camera->m_zn);
		D3DXVECTOR3 p2=D3DXVECTOR3(dx*m_Camera->m_zf*tmp,dy*m_Camera->m_zf*tmp,m_Camera->m_zf);
		D3DXVec3TransformCoord(&p1,&p1,&invMatrix);
		D3DXVec3TransformCoord(&p2,&p2,&invMatrix);
		return new Ray(p1,p2-p1);
	}

	D3DXVECTOR2 Coordinate::WorldToScreenCoord(D3DXVECTOR3* pos)
	{
		D3DXVECTOR3 tmp;
		D3DXVec3TransformCoord(&tmp,pos,m_Camera->GetViewMatrix());
		float tf=tanf(m_Camera->m_fovy/2);
		if(tmp.z<1)
			tmp.z=1;
		float dx=tmp.x/(tf*tmp.z);
		float dy=tmp.y/(tf*tmp.z);
		float x=(dx/m_Camera->m_aspect+1.0f)*(float)m_screenWidth/2.0f;
		float y=(1.0f-dy)*(float)m_screenHeight/2.0f;
		return D3DXVECTOR2(x,y);
	}
}